$(function() {
    $('#activator').click(function(){
        $('#box').animate({'top':'0px'},500);
    });
    $('#boxclose').click(function(){
        $('#box').animate({'top':'-700px'},500);
    });
});

$(document).ready(function(){
    //Hide (Collapse) the toggle containers on load
    $(".toggle_container").hide();
    //Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
    $(".trigger").click(function(){
        $(this).toggleClass("active").next().slideToggle("slow");
            return false; //Prevent the browser jump to the link anchor
    });

    $('#album_name').multiselect({
        enableHTML: true,
        enableFiltering: true,
        enableCaseInsensitiveFiltering: true,
        buttonClass: 'btn btn-default btn-sm',
        buttonWidth: '100%',
        buttonText: function(options, select) {
            return '相册 ' + (options.length > 0 ? options.length : '');
        }
	});
	$('#volume_name').multiselect({
        enableHTML: true,
        enableFiltering: true,
        enableCaseInsensitiveFiltering: true,
        buttonClass: 'btn btn-default btn-sm',
        buttonWidth: '100%',
        enableCollapsibleOptGroups: true,
        collapseOptGroupsByDefault: true,
	});
	$('#tag_name').multiselect({
        enableHTML: true,
        enableFiltering: true,
        enableCaseInsensitiveFiltering: true,
        buttonClass: 'btn btn-default btn-sm',
        buttonWidth: '100%',
        buttonText: function(options, select) {
            return '标签 ' + (options.length > 0 ? options.length : '');
        }
	});
	$('#actress_name').multiselect({
        enableHTML: true,
        enableFiltering: true,
        enableCaseInsensitiveFiltering: true,
        buttonClass: 'btn btn-default btn-sm',
        buttonWidth: '100%',
        buttonText: function(options, select) {
            return '模特 ' + (options.length > 0 ? options.length : '');
        }
	});

    $('#single_actress_select').multiselect({
        enableHTML: true,
        enableFiltering: true,
        enableCaseInsensitiveFiltering: true,
        buttonWidth: '100%',
        buttonClass: 'btn btn-default',
    })

});


let lastKey = null;
let lastTime = 0;
document.addEventListener("keydown", function(event) {

    // SOS
	let key = event.key,
        time = event.timeStamp;
    if (key === "Escape"){window.close()}
	else if (lastKey === key && key === 'Escape' && time - lastTime < 1000) {
        window.open('https://www.chiphell.com')
        window.location.href = 'https://store.epicgames.com/zh-CN/';
    }
    lastKey = key; // 最后按下的键
    lastTime = time;  // 最后按键的时间

    if(document.activeElement.tagName === 'BODY' || document.activeElement.type ==='checkbox') {
        if (event.key === "r" || event.key === "R") {
            location.reload();
        }
    }
})


//checkbox选中事件
let pic_ct = 0;

function checkbox_count(){
    pic_ct = $("#batch_deal input[type='checkbox']:checked").length; //checkbox 选中数量
    $('#chk_count').val('选中 ' +pic_ct);
    if (pic_ct === 0){
        // $('#batch_tools').addClass("hidden");
        $('#album_name').multiselect("deselectAll",false).multiselect('refresh');
        $('#volume_name').multiselect("select", "").multiselect('refresh');
        $('#tag_name').multiselect("deselectAll",false).multiselect('refresh');
        $('#actress_name').multiselect("deselectAll",false).multiselect('refresh');
        $('#compare_btn').addClass('hidden');
        $('#cover_btn').addClass("hidden")  //选中为非1个时，隐藏设为封面的按钮
    }
    else if (pic_ct === 1){
        $('#compare_btn').addClass('hidden');
        $('#cover_btn').removeClass("hidden")  //选中一个才出现设为封面的按钮
    }
    else if (pic_ct === 2){
        $('#compare_btn').removeClass('hidden');
        $('#cover_btn').addClass("hidden")  //选中为非1个时，隐藏设为封面的按钮
    }
    else {
        $('#compare_btn').addClass('hidden');
        $('#cover_btn').addClass("hidden")  //选中为非1个时，隐藏设为封面的按钮
    }
}

function tools_btn(){
    $(".pics_chk").click(function () {
        checkbox_count();
        if ($("#batch_deal input[type='checkbox']").is(':checked')) {
            $('#batch_tools').removeClass("hidden");
        }
    });

    $("#select_all").click(function () {
        $("#batch_deal input[type='checkbox']").prop("checked", true);
        checkbox_count();
    });

    $("#cancel_select").click(function () {
        $("#batch_deal input[type='checkbox']").prop("checked", false);
        checkbox_count();
    })
}

function updateNote(pic_id, note){
    $.ajax({
        type: "POST",
        url: js_pic['note_edit_url'],
        dataType: "json",
        contentType: "application/json",
        data:JSON.stringify({"id":pic_id,"note":note}),
        success: function (result){
            if (result['status'] === 0){alert(result['info'])} //报错才弹框
        }
    })
}

function setUrlParams(params) {
    let urlObj = new URL(window.location.href, window.location.origin);
    for (let key in params) {
        let value = params[key];
        if (value === ''){
            urlObj.searchParams.delete(key)
        }else{
            urlObj.searchParams.set(key, params[key]);
        }
    }
    window.location.href = urlObj.toString();
}

function skip2newWindow(url){
    window.open(url)
}


//////////  ajax加载更多图片 start


if (typeof(js_more_pics) == "undefined") {js_more_pics = {}}

let $tiles = $('#tiles'),
    $handler = $('li', $tiles),
    $main = $('#main'),
    $window = $(window),
    $document = $(document),
    options = {
        //align: 'left',
        autoResize: true, // This will auto-update the layout when the browser window is resized.
        container: $main, // Optional, used for some extra CSS styling
        offset: 10, // Optional, the distance between grid items
        itemWidth:200 // Optional, the width of a grid item
    };
  /**
   * Reinitializes the wookmark handler after all images have loaded
   */
function applyLayout() {
    $tiles.imagesLoaded(function() {
        // Destroy the old handler
        if ($handler.wookmarkInstance) {
            $handler.wookmarkInstance.clear();
        }

         // Create a new layout handler.
         $handler = $('li', $tiles);
         $handler.wookmark(options);
    });
}

function load_more_pics() {
    let local_data = {'page': js_more_pics['page'] + 1},
        data = $.extend(local_data, js_more_pics['ajax_post_data']);
    $.ajax({
        url: js_more_pics['url'],
        type: 'GET',
        dataType: "json",
        data: data,
        async:false,
        success:function(pic_data){
            if (pic_data !== '[]') {
                $tiles.append(pic_data);
                applyLayout();
                js_more_pics['page'] += 1;
                tools_btn();
            }
        }
    })
}


(function ($){

    // Call the layout function for the first time
    applyLayout();
    tools_btn();

      /**
       * When scrolled all the way to the bottom, add more tiles
       */

    function onScroll() {
        if (!js_more_pics['page']) {}  // 不需要加载更多图片的页面
        else{
            let totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());     //浏览器的高度加上滚动条的高度

            if ($(document).height() === totalheight) {  //当文档的高度等于总的高度的时候，开始动态加载数据
                load_more_pics()
            }
        }
    }


// Capture scroll event.
$window.bind('scroll.wookmark', onScroll);
})(jQuery);

//////////  ajax加载更多图片 end



// album 和 picture共用
function rating(object_label, object_id, score){
    $.ajax({
        url:js_pic["rating_url"],
        type: 'POST',
        async:false,
        contentType: "application/json",
        data: JSON.stringify({'label': object_label,'id': object_id, 'score': score}),
        success:function(){
        $('#rate-' + object_id).attr("class","rating star-"+score)
        }
    })
}

// 双击图片的note部分，变成textarea编辑
function noteDblClick(event) {
    if (event.target.className === 'album_pic_note') {
        // 监听note部分的双击事件
        let targetElement = event.target,
            pic_id = targetElement.getAttribute('data-id'),
            note = targetElement.textContent

        targetElement.innerHTML = '<textarea class="form-control input-sm">'+note+'</textarea>'
        let textarea = targetElement.querySelector('textarea')
        textarea.selectionStart = 0;
        textarea.selectionEnd = note.length;
        textarea.focus();

        textarea.addEventListener('blur', function() {
            // 当<textarea>失去焦点时
            if(this.value === note || this.value === ''){
                targetElement.innerText = note
            }else{
                updateNote(pic_id, this.value)
                targetElement.innerText = this.value
            }
        });
    }
}


////////// album 部分 start
if (typeof(js_album) == "undefined") { js_album = {}}


function batch_deal_checked(){
    let pics_list = [];
    $("#batch_deal input[type='checkbox']:checked").each(function(){ pics_list.push($(this).val()) });
    return pics_list
}


$('#join_albums_btn').click(function () {
    if (typeof(js_join_albums_btn_url) == "undefined") { js_join_albums_btn_url = ''}
	let albums = $('#album_name').val(),
	    tags = $('#tag_name').val(),
	    volumes = $('#volume_name').val(),
        actresses = $('#actress_name').val(),
	    pics = batch_deal_checked();
	if (albums !== '' || tags !== '' || volumes !== '' || actresses !== ''){
		$.ajax({
			url: js_album['join_albums_url'],
			type: 'POST',
			dataType:"json",
			async:false,
			contentType: "application/json",
			data: JSON.stringify({'albums':albums,'tags':tags,'volumes': volumes, 'actresses': actresses, 'pics':pics}),
			success: function (result) {
				alert(result['info']);
			}
		})
	} else { alert('未选择相册或标签或卷') }
});


$('#move_out_btn').click(function () {
    let msg = "确定移出选中的图片吗？",
        pics_list = batch_deal_checked();
    if (confirm(msg)===true){
		$.ajax({
			url: js_album['move_out_album_url'],
			type: 'POST',
			async:false,
			dataType:"json",
			contentType: "application/json",
			data: JSON.stringify({'label': js_album['label'], 'id':js_album['id'], 'pic': pics_list}),
			success: function (result) {
				alert(result['info']);
				location.reload();
			}
		})
	} else {}
});


$('#delete_tag_album').click(function () {
    let msg = "确定删除 " + js_album['label'] +":" + js_album['title']+" 吗？";
    if (confirm(msg)===true){
		$.ajax({
			url: js_album['delete_tag_album_url'],
			type: 'GET',
			async:false,
			dataType:"json",
			data: {"label": js_album['label'], "id": js_album['id']},
			success: function (result) {
				alert(result['info']);
				window.location = window.history.back();
			}
		})
	} else {}
});


$('#modify_album_btn').click(function () {
    let name = $('#album_name_text').val(),
        note = $('#album_note_text').val(),
        actress_id = $('#single_actress_select').val(),
        option_group = $('#album_meta_option_group').val(),
        archived = $('#album_archive_chk').is(':checked'),
        cancel_cover = $('#cancel_cover_chk').is(':checked'),
        order_by = $('#album_order_by input[name="order_by"]:checked').val();
    if (name !== '' && name !== ' '){
        $.ajax({
            url: js_album['modify_album_url'],
            type: 'POST',
            async:false,
            dataType:"json",
            contentType: "application/json",
            data: JSON.stringify({
                "label": js_album['label'], "id": js_album['id'], "name":name, "note":note,
                "actress_id": actress_id, "option_group": option_group, "archived": archived,
                "cancel_cover": cancel_cover,"order_by": order_by,
            }),
            success: function (result) {
                if (result['status'] === 1){
                    location.reload();
                }
            }
        })
    }
});


$('#cover_btn').click(function () {
	let pic_id = $("#batch_deal input[type='checkbox']:checked").val();
    if (pic_id !== js_album['cover_id'] ) {
        $.ajax({
            url: js_album['set_cover_url'],
            type: 'GET',
            async:false,
            dataType:"json",
            data: {"label": js_album['label'],"id": js_album['id'],"cover":pic_id },
            success: function (result) {
                alert(result['info']);
            }
        })
    } else { alert('请勿重复设置')}
});


$('#download_pics').click(function (){
    let pics_list = batch_deal_checked();
    window.open(js_album['download_url'] + '?pics=' + pics_list)
})


$('#delete_pics_btn').click(function () {
	let pics_list = batch_deal_checked();
    if (confirm('确定删除选中的图片吗？')===true) {
        $.ajax({
            url: js_album['delete_pics_url'],
            type: 'POST',
            async:false,
            dataType:"json",
            contentType: "application/json",
			data: JSON.stringify({"pics": pics_list}),
            success: function (result) {
                alert(result['info']);
            }
        })
    }
});

$('#compare_btn').click(function (){
    let pics = batch_deal_checked();
    if (pics.length === 2){
        window.open('/pic/compare/' + Math.max(...pics) + '/' + Math.min(...pics));
        $("#batch_deal input[type='checkbox']").prop("checked",false);
        checkbox_count();
    }
})


$('#recycle_restore_btn').click(function () {
    let pics_list = batch_deal_checked();
    if (confirm('确定恢复选中的图片吗？')===true) {
        $.ajax({
            url: js_album['recycle_restore'],
            type: 'POST',
            async: false,
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({"pics": pics_list}),
            success: function (result) {
                alert(result['info']);
                if (result['status'] === 1){ location.reload()}
            }
        })
    }
})

$('#recycle_delete_btn').click(function () {
    let pics_list = batch_deal_checked();
    if (confirm('确定彻底删除选中的图片吗？')===true) {
        $.ajax({
            url: js_album['recycle_delete'],
            type: 'POST',
            async: false,
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({"pics": pics_list}),
            success: function (result) {
                alert(result['info']);
                if (result['status'] === 1){ location.reload()}
            }
        })
    }
})

$('#recycle_empty_btn').click(function () {
    if (confirm('确定清空回收站吗？')===true) {
        $.ajax({
            url: js_album['recycle_delete'],
            type: 'POST',
            async: false,
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({"all": 1}),
            success: function (result) {
                alert(result['info']);
                if (result['status'] === 1){ location.reload()}
            }
        })
    }
})


function load_filter(a_name, url){

    function f(){
        $('#batch_tools').removeClass('hidden');
        if (a_name){
            $('#volume_name_div').find('input[type="text"]').val(a_name + ':').trigger('input');
        }
    };

    $.ajax({
        url: url,
        type: 'GET',
        async:false,
        dataType:"json",
        success: function (result) {
            $('#album_name').html(result['albums']);
            $('#tag_name').html(result['tags']);
            $('#actress_name').html(result['actresses']);
            $('#volume_name').append(result['volumes']);
            setTimeout(f,2000);
        }
    })
}

////////// album 部分 end


////////// picture 部分 start
if (typeof(js_pic) == "undefined") { js_pic = {}}

function onDelete_dbRecord(pic_id) {
    let msg = "确定删除图片(ID:"+pic_id+")吗？";
    if (confirm(msg)==true){
        $.ajax({
            url: js_pic['delete_api_url'],
            type: 'GET',
            async:false,
            data: 'id=' + pic_id,
            dataType:"json",
            success: function (result) {
                alert(result['info']);
                // window.history.back(-1);
            }
        });
    } else {}
}

function onRotatePic(pic_id){
    let msg = "确定旋转图片吗？";
    if(confirm(msg)==true){
        $.ajax({
            url: js_pic['rotate_pic_api_url'],
            type: 'GET',
            async: false,
            data: 'pic_id=' + pic_id,
            dataType:"json",
            success: function (result) {
                location.reload();
            }
        })
    } else {}
}

function onScaleXPic(pic_id){
    let msg = "确定水平翻转图片吗？";
    if(confirm(msg)==true){
        $.ajax({
            url: js_pic['scalex_pic_api_url'],
            type: 'GET',
            async: false,
            data: 'pic_id=' + pic_id,
            dataType:"json",
            success: function (result) {
                location.reload();
            }
        })
    } else {}
}

$('.pic_modal_submit').click(function () {
    let data =[];//定义一个数组
    $("#pic_modal input[type='checkbox']:checked").each(function(){ data.push($(this).val()) });
    $.ajax({
        url: js_pic['album_tag_update_url'],
        type: "POST",
        async:false,
        contentType: "application/json",
        dataType:"json",
        data: JSON.stringify({'pic_id': js_pic["pic_id"],'data':data}),
        success: function(result) {
            if (result['status'] === 1){
                $('#pic_actresses').html(result['pic_actresses'])
                $('#pic_albums').html(result['pic_albums'])
                $('#pic_volumes').html(result['pic_volumes'])
                $('#pic_tags').html(result['pic_tags'])
                $('#pic_modal').modal('hide')
            }
            else{alert(result['info']) }
        }
    })
});


$('#create_album_btn').click(function () {
    let text = $('#create_album').val();
    if (text != '' && text != ' ') {
        $("#new_album").html('<label class="checkbox-inline"><input type="checkbox" checked class="pic_info_chk" name="album_chk" value="album-' + text +'">'+ text + '</label>');
    }
});
$('#create_tag_btn').click(function () {
    let text = $('#create_tag').val();
    if (text != '' && text != ' ') {
        $("#new_tag").html('<label class="checkbox-inline"><input type="checkbox" checked class="pic_info_chk" name="tag_chk" value="tag-' + text +'">'+ text + '</label>');
    }
});

$('#pic_modal').on('show.bs.modal', function () {
    let html_prefix = '<div class="col-xs-6 col-sm-12"><div class="form-group"><label class="checkbox-inline"><input type="checkbox" class="pic_info_chk" ',
        html_suffix = '</label></div></div>';
    // {#原始html <div class="col-xs-6 col-sm-12"><div class="form-group"><label class="checkbox-inline"><input type="checkbox" class="pic_info_chk" name="album_chk" value="album-WANIMAL">WANIMAL</label></div></div>#}
    $.get(js_pic['all_categories_url'], function(result) {
        $.each(result['albums'], function (index, element) {
            let is_checked = pic_albums.includes(element.id)  ? 'checked': '';
            $('#album_div').append(html_prefix + is_checked + ' name="album_chk" value="album-' + element.name + '">' + element.name +html_suffix)
        });

        $.each(result['tags'], function (index, element) {
            let is_checked = pic_tags.includes(element.id)  ? 'checked': '';
            $('#tag_div').append(html_prefix + is_checked + ' name="tag_chk" value="tag-' + element.name + '">' + element.name +html_suffix)
        });

        $.each(result['actresses'], function (index, element) {
            let is_checked = pic_actresses.includes(element.id)  ? 'checked': '';
            $('#actress_div').append(html_prefix + is_checked + ' name="actress_chk" value="actress-' + element.name + '">' + element.name +html_suffix)
        });

        $.each(result['volumes'], function (index, element) {
            let is_checked = pic_volumes.includes(element.id)  ? 'checked': '';
            $('#volume_div').append(html_prefix + is_checked + ' name="volume_chk" value="volume-' + element.id + '">' + element.name +html_suffix)
        });
    });
})

function collapse_div(div_name){
    $('#actress_div').removeClass('in');
    $('#tag_div').removeClass('in');
    $('#volume_div').removeClass('in');
    $('#album_div').removeClass('in');
    $('#'+div_name).addClass('in');
}

////////// picture 部分 end



////////// work 部分 start

if (typeof(js_work) == "undefined") { js_work = {}}

$('input[name="label"][type="radio"]').change(function (){
    let choose = $(this).val();
    if (choose == 'album' || choose == 'tag' || choose == 'actress'){$('#volume_only').addClass('hidden')}
    else{$('#volume_only').removeClass('hidden')}
});


$('#create_album_commit').click(function () {
    let name = $("#name_album_or_tag").val(),
        label = $("#add_album input[name='label']:checked").val(),
        actress_id = $("#single_actress_select").val();
    if (name != ''){
        if ($("#add_album input[type='radio']").is(':checked')) {
            $.ajax({
                url: js_work['create_album_url'],
                type: "POST",
                async:false,
                dataType:"json",
                contentType: "application/json",
                data: JSON.stringify({"label": label, "name": name, "actress_id": actress_id}),
                success: function (result) {
                    alert(result['info']);
                    location.reload();
                }
            })
        } else {alert ('请选择相册或标签')}
    } else {alert ('请填写名称')}
});


$('#check_files_btn').click(function () {
    $.ajax({
        url: js_work['check_files_url'],
        type: "GET",
        success: function() {
            alert('任务创建成功，请稍后刷新页面')
        }
    })
});


$('#new_setting_commit').click(function () {
    $.ajax({
        url: js_work['new_setting_url'],
        type: "POST",
        dataType: "json",
        data: $('#new_setting_form').serialize(),
        async:false,
        success: function(result) {
            if(result['status']=== 1){location.reload(); }
            else{
                alert('创建setting失败');
                console.log(result['info'])
                }
        }
    })
});


function editSetting_btn(id){
    let msg = "确定修改该项配置吗？",
        new_value = $('#setting_value_'+ id).val();
    if (new_value != ''){
        if (confirm(msg)==true){
            $.ajax({
                url: js_work['edit_setting_url'],
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({'id': id, 'value': new_value}),
                async:false,
                success: function(result) {
                    if(result['status']== 1){location.reload(); }
                    else{
                        alert('创建setting失败');
                        console.log(result['info'])
                        }
                }
            })
        } else {}
    }
}


$('#scan_task_btn').click(function () {
    $('#refresh_temp_info').click();
    $.ajax({
        url: js_work['scan_task_url'],
        type: "GET",
        dataType: 'json',
        async:false,
        success: function(result) {
           //alert(result['msg']);
           $('#flash_msg').html('<div class="alert alert-info alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>开始导入图片</div>');
        }
    })
});


$('#refresh_temp_info').click(function () {
    $('.close').click();
    $.ajax({
        url: js_work['count_temp_url'],
        type: "GET",
        dataType: 'json',
        success: function(result) {
            $('#temp_file_count').text(result)
        }
    });
    $.ajax({
        url: js_work['count_recycle_url'],
        type: "GET",
        dataType: 'json',
        success: function(result) {
            $('#recycle_file_count').text(result)
        }
    })

});


$('#create_thumbnail_btn').click(function () {
    $.ajax({
        url: js_work['create_thumbnail_url'],
        type: "GET",
        async:false,
        success: function() {
            location.reload();
        }
    })
});


$('#delete_thumbnail_btn').click(function () {
    $.ajax({
        url: js_work['delete_thumbnail_url'],
        type: "GET",
        async:false,
        success: function() {
            location.reload();
        }
    })
});


$('#move_to_recycle_btn').click(function () {
    $.ajax({
        url: js_work['move_to_recycle_url'],
        type: "GET",
        async:false,
        success: function() {
            location.reload();
        }
    })
});


$('#add_work_submit').click(function () {
    if ($('#work_title').val() !== '' && $('#work_content').val() !==''){
        $('#add_work_submit').attr("disabled",true);
        setTimeout("$('#add_work_submit').removeAttr('disabled')",2000);
        let data = $('#work_modal form').serialize();
        $.ajax({
            url: js_work['add_work_url'],
            type: "POST",
            dataType: "json",
            data: data,
            async:false,
            success: function(result) {
                if (result['status'] === 1){
                    location.reload()
                }
                else{alert(result['msg'])}
            }
        })
    } else{alert('标题或内容不能为空')}
});

function upload_files_count() {
    let files_count = document.getElementById("input_file").files.length;
    if (files_count === 0){$('#upload_files_btn').addClass("hidden").val('Upload')} else{ $('#upload_files_btn').removeClass("hidden").val('Upload 0/' + files_count)}
}

$('#cache_clear_btn').click(function () {
    $.get(js_work['cache_clear_url'], function (r) {
        if (r['status'] === 1){alert('缓存清理成功')}
    })
});

$('#external_image_download').click(function (){
    let url = $('#external_image_url').val();
    if (url !== '') {
        $.ajax({
            url: js_work['image_origin_url'],
            type: "GET",
            data: JSON.stringify({'url': url}),
            async: false,
            success: function () {
                if (r['status'] === 1) {
                    // 拿到原图url，开始下载
                    console.log(url)
                }
            }
        })
    }
})

////////// work 部分 end